/******************************************************************************
*   Helper Functions
*   This file holds useful defines, macros and functions that can be used
*   by anybody!
*   Contains: Booleans, Nulls, SAFE_FREE, min, max, quick-half, quick-odd check
*******************************************************************************/

#ifndef HELPER_FUNCTIONS_H
#define HELPER_FUNCTIONS_H

// Define bool as int
#ifndef BOOL
#define BOOL int
#endif
// Make lowercase also compatable
#ifndef bool
#define bool BOOL
#endif

// Define True
#ifndef TRUE
#define TRUE 1
#endif
// Make lowercase also compatable
#ifndef true
#define true TRUE
#endif

// Define False
#ifndef FALSE
#define FALSE 0
#endif
// Make lowercase also compatable
#ifndef false
#define false FALSE
#endif

#ifndef u16
#define u16 unsigned short
#endif

#ifndef u32
#define u32 unsigned int
#endif

// Define NULL
#ifndef NULL
#define NULL (void*)0
#endif

// 2-D Vector
// useful for holding coordinates
typedef struct STRUCT_VECTOR2
{
    int x, y;
} Vector2;

// Min/Max functions
#define MIN(X,Y) ((X) < (Y) ? (X) : (Y))
#define MAX(X,Y) ((X) > (Y) ? (X) : (Y))

// Quick macros to return half and check if is odd
#define HALF(x) (x<<1)
#define IS_ODD(x) (x&1)

// SuperMod performs a mod but first adds Y to X, then performs the mod
// Note: No values are modified
#define SUPER_MOD(X,Y)((X + Y) % Y)

// Performs null check then fress and sets to zero ( the while is just to make sure we need a semicolon at the end )
// Note: ALWAYS USE SAFE FREE FOR POINTERS YA IDIOT!
#define SAFE_FREE(x) do { if ((x) != NULL) {free(x); x=NULL;} } while(0)

// Macro for Running Code only if DEBUG is set
#ifdef DEBUG
#define DEBUG_CODE(code) { code }
#else
#define DEBUG_CODE(code)
#endif

// Distance function
int distance( int x1, int y1, int x2, int y2 )
{
	int xd = x2 - x1;
	int yd = y2 - y1;
	
	pow( xd, 2 );
	pow( y2, 2 );
	
	return sqrt( pow( xd, 2 ) + pow( yd, 2 ) );
}

// Returns a value, but ensures the value is between the two ranges.
int clamp( int const value, int const lower, int const upper )
{
    if ( value < lower )
    {
        return lower;
    }

    if ( value > upper )
    {
        return upper;
    }

    return value;
}

// Returns random number
// note: Should not be used, there is a better way
int getRandom( int lower, int upper )
{
    if ( lower == upper )
        return lower;
    return rand() % upper + lower;
}

#endif
